package com.supertange.miniapp.wepet.modules.wepet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.supertange.miniapp.wepet.common.idworker.Sid;
import com.supertange.miniapp.wepet.common.utils.Assert;
import com.supertange.miniapp.wepet.common.utils.PagedResult;
import com.supertange.miniapp.wepet.common.utils.TimeAgoUtils;
import com.supertange.miniapp.wepet.modules.wepet.entity.CommentsEntity;
import com.supertange.miniapp.wepet.modules.wepet.entity.SearchRecordsEntity;
import com.supertange.miniapp.wepet.modules.wepet.entity.UsersLikeVideoEntity;
import com.supertange.miniapp.wepet.modules.wepet.entity.Videos;
import com.supertange.miniapp.wepet.modules.wepet.entity.vo.CommentsVO;
import com.supertange.miniapp.wepet.modules.wepet.entity.vo.VideosVO;
import com.supertange.miniapp.wepet.modules.wepet.mapper.*;
import com.supertange.miniapp.wepet.modules.wepet.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("videoService")
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideosMapper videosMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private VideosMapperCustom videosMapperCustom;

    @Autowired
    private SearchRecordsMapper searchRecordsMapper;

    @Autowired
    private UsersLikeVideosMapper usersLikeVideosMapper;

    @Autowired
    private CommentsMapper commentMapper;

    @Autowired
    private CommentsMapperCustom commentMapperCustom;

    @Autowired
    private Sid sid;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public String saveVideo(Videos video) {

        String id = sid.nextShort();
        video.setId(id);
        videosMapper.insert(video);
        usersMapper.addVideoCount(video.getUserId());
        return id;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateVideo(String videoId, String coverPath) {

        Videos video = new Videos();
        video.setId(videoId);
        video.setCoverPath(coverPath);
        videosMapper.updateById(video);
    }

    @Override
    @Transactional(propagation =Propagation.REQUIRED)
    public void deleteVideo(String videoId,String userId) {
        //删除视频
        videosMapper.delete(new LambdaQueryWrapper<Videos>().eq(Videos::getId, videoId).eq(Videos::getUserId, userId));

        //删除喜欢
        usersLikeVideosMapper.delete(new LambdaQueryWrapper<UsersLikeVideoEntity>().eq(UsersLikeVideoEntity::getVideoId,videoId));

        //用户视频数目减一
        usersMapper.reduceVideoCount(userId);

        //删除评论
        commentMapper.delete(new LambdaQueryWrapper<CommentsEntity>().eq(CommentsEntity::getVideoId,videoId));
    }

    @Override
    public Videos queryOneVideo(String videoId) {
        return videosMapper.selectOne(new LambdaQueryWrapper<Videos>().eq(Videos::getId, videoId));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public PagedResult getAllVideos(Videos video, Integer isSaveRecord, Integer isShuffle,
                                    Integer page, Integer pageSize) {

        // 保存热搜词
        String desc = video.getVideoDesc();
        String userId = video.getUserId();
        if (isSaveRecord != null && isSaveRecord == 1) {
            SearchRecordsEntity record = new SearchRecordsEntity();
            String recordId = sid.nextShort();
            record.setId(recordId);
            record.setContent(desc);
            searchRecordsMapper.insert(record);
        }
        PageHelper.startPage(page, pageSize);
        List<VideosVO> list = null;
        if (isShuffle != null && isShuffle == 1) {
            list = videosMapperCustom.queryShuffleVideos(desc, userId);
        } else {
            list = videosMapperCustom.queryAllVideos(desc, userId);
        }

        PageInfo<VideosVO> pageList = new PageInfo<>(list);

        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(list);
        pagedResult.setRecords(pageList.getTotal());

        return pagedResult;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedResult queryMyLikeVideos(String userId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<VideosVO> list = videosMapperCustom.queryMyLikeVideos(userId);

        PageInfo<VideosVO> pageList = new PageInfo<>(list);

        PagedResult pagedResult = new PagedResult();
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(list);
        pagedResult.setPage(page);
        pagedResult.setRecords(pageList.getTotal());

        return pagedResult;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedResult queryMyFollowVideos(String userId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<VideosVO> list = videosMapperCustom.queryMyFollowVideos(userId);

        PageInfo<VideosVO> pageList = new PageInfo<>(list);

        PagedResult pagedResult = new PagedResult();
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(list);
        pagedResult.setPage(page);
        pagedResult.setRecords(pageList.getTotal());

        return pagedResult;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<String> getHotwords() {
        return searchRecordsMapper.getHotwords();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void userLikeVideo(String userId, String videoId, String videoCreaterId) {
        // 1. 保存用户和视频的喜欢点赞关联关系表
        String likeId = sid.nextShort();
        UsersLikeVideoEntity usersLikeVideoEntity = usersLikeVideosMapper.selectOne(new QueryWrapper<UsersLikeVideoEntity>().eq("user_id", userId).eq("video_id", videoId));
        if (usersLikeVideoEntity != null) Assert.isError("不能重复赞");
        UsersLikeVideoEntity ulv = new UsersLikeVideoEntity();
        ulv.setId(likeId);
        ulv.setUserId(userId);
        ulv.setVideoId(videoId);
        usersLikeVideosMapper.insert(ulv);

        // 2. 视频喜欢数量累加
        videosMapperCustom.addVideoLikeCount(videoId);

        // 3. 用户受喜欢数量的累加
        usersMapper.addReceiveLikeCount(videoCreaterId);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void userUnLikeVideo(String userId, String videoId, String videoCreaterId) {
        // 1. 删除用户和视频的喜欢点赞关联关系表

        UsersLikeVideoEntity usersLikeVideoEntity = usersLikeVideosMapper.selectOne(new QueryWrapper<UsersLikeVideoEntity>().eq("user_id", userId).eq("video_id", videoId));
        if (usersLikeVideoEntity == null) Assert.isError("不能重复取消");
        usersLikeVideosMapper.delete(new QueryWrapper<UsersLikeVideoEntity>().eq("user_id", userId).eq("video_id", videoId));
        // 2. 视频喜欢数量累减
        videosMapperCustom.reduceVideoLikeCount(videoId);

        // 3. 用户受喜欢数量的累减
        usersMapper.reduceReceiveLikeCount(videoCreaterId);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void saveComment(CommentsEntity comment) {
        String id = sid.nextShort();
        comment.setId(id);
        commentMapper.insert(comment);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedResult getAllComments(String videoId, Integer page, Integer pageSize) {

        PageHelper.startPage(page, pageSize);

        List<CommentsVO> list = commentMapperCustom.queryComments(videoId);

        for (CommentsVO c : list) {
            String timeAgo = TimeAgoUtils.format(c.getCreateTime());
            c.setTimeAgoStr(timeAgo);
        }

        PageInfo<CommentsVO> pageList = new PageInfo<>(list);

        PagedResult grid = new PagedResult();
        grid.setTotal(pageList.getPages());
        grid.setRows(list);
        grid.setPage(page);
        grid.setRecords(pageList.getTotal());

        return grid;
    }




}
